package com.fengstyle.demo.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author yuhf
 */
@Component
@ServerEndpoint("/ws")
public class WsServerEndpoint {

    private static int onlineCount = 0;

    private final String id;

    public WsServerEndpoint(){
        this.id = UUID.randomUUID().toString().replace("-", "");
    }

    private static CopyOnWriteArraySet<WsServerEndpoint> webSocketSet = new CopyOnWriteArraySet<>();

    @OnMessage
    public void onMessage(String msg, Session session) throws IOException {
        webSocketSet.forEach(ws -> {
            if(ws.id.equals(this.id)){
                System.out.println("收到 " +id+ " 消息：" + msg);
            }
        });
        session.getBasicRemote().sendText("回复消息：" + msg);
    }

    @OnOpen
    public void onOpen(Session session){
        System.out.println("连接成功");
        webSocketSet.add(this);
        addOnlineCount();
        System.out.println("有新连接加入，当前在线人数：" + onlineCount);
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("连接关闭");
        webSocketSet.remove(this);
        subOnlineCount();
        System.out.println("有连接关闭，当前在线人数：" + onlineCount);
    }

    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生异常");
        error.printStackTrace();
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WsServerEndpoint.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WsServerEndpoint.onlineCount--;
    }

}
